package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"learn-go-demo/pkg/config"
)

func main() {
	var (
		action     = flag.String("action", "create", "Action to perform: create, validate, show")
		configPath = flag.String("path", "./configs/config.yaml", "Path to config file")
		env        = flag.String("env", "development", "Environment: development, production, test")
	)
	flag.Parse()

	switch *action {
	case "create":
		createConfig(*configPath, *env)
	case "validate":
		validateConfig(*configPath)
	case "show":
		showConfig(*configPath)
	default:
		fmt.Printf("Unknown action: %s\n", *action)
		flag.Usage()
		os.Exit(1)
	}
}

func createConfig(path, env string) {
	if err := config.CreateConfigFile(path); err != nil {
		log.Fatalf("Failed to create config file: %v", err)
	}
	fmt.Printf("✅ Config file created: %s\n", path)
	fmt.Printf("💡 You can now edit the file to customize settings for %s environment\n", env)
}

func validateConfig(path string) {
	cfg, err := config.LoadConfig("")
	if err != nil {
		log.Fatalf("❌ Config validation failed: %v", err)
	}
	
	fmt.Printf("✅ Config validation passed\n")
	fmt.Printf("📋 Configuration summary:\n")
	fmt.Printf("  App: %s v%s (%s)\n", cfg.App.Name, cfg.App.Version, cfg.App.Environment)
	fmt.Printf("  Database: %s@%s:%d/%s\n", cfg.Database.User, cfg.Database.Host, cfg.Database.Port, cfg.Database.Database)
	fmt.Printf("  gRPC Port: %d\n", cfg.GRPC.Port)
	fmt.Printf("  HTTP Port: %d\n", cfg.HTTP.Port)
	fmt.Printf("  Etcd: %v\n", cfg.Etcd.Endpoints)
}

func showConfig(path string) {
	cfg, err := config.LoadConfig("")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}
	
	fmt.Printf("📋 Current Configuration:\n")
	fmt.Printf("=========================\n")
	fmt.Printf("Application:\n")
	fmt.Printf("  Name: %s\n", cfg.App.Name)
	fmt.Printf("  Version: %s\n", cfg.App.Version)
	fmt.Printf("  Environment: %s\n", cfg.App.Environment)
	fmt.Printf("  Log Level: %s\n", cfg.App.LogLevel)
	fmt.Printf("\n")
	
	fmt.Printf("Database:\n")
	fmt.Printf("  Host: %s\n", cfg.Database.Host)
	fmt.Printf("  Port: %d\n", cfg.Database.Port)
	fmt.Printf("  User: %s\n", cfg.Database.User)
	fmt.Printf("  Database: %s\n", cfg.Database.Database)
	fmt.Printf("  Max Open Connections: %d\n", cfg.Database.MaxOpenConns)
	fmt.Printf("  Max Idle Connections: %d\n", cfg.Database.MaxIdleConns)
	fmt.Printf("  Connection Max Lifetime: %d minutes\n", cfg.Database.ConnMaxLifetime)
	fmt.Printf("\n")
	
	fmt.Printf("Services:\n")
	fmt.Printf("  gRPC Port: %d\n", cfg.GRPC.Port)
	fmt.Printf("  HTTP Port: %d\n", cfg.HTTP.Port)
	fmt.Printf("\n")
	
	fmt.Printf("Etcd:\n")
	fmt.Printf("  Endpoints: %v\n", cfg.Etcd.Endpoints)
	fmt.Printf("  Timeout: %d seconds\n", cfg.Etcd.Timeout)
}
